package mysql

import (
	"database/sql"
	"ever-checksum/errs"
)

func QueryForSet(db *sql.DB, sql string) []map[string]string {
	rows, err := db.Query(sql) // 查询源端情况，默认源端、目标端表结构一致
	defer rows.Close()
	errs.CheckErr(err)
	columns, _ := rows.Columns()

	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	var recordSet []map[string]string
	for rows.Next() {
		err = rows.Scan(scanArgs...)
		record := make(map[string]string)
		for i, col := range values {
			if col != nil {
				record[columns[i]] = string(col.([]byte))
			}
		}
		recordSet = append(recordSet, record)
	}
	return recordSet
}

func QueryForCheckResult(colNames []string, db *sql.DB, sql string) ([]interface{}, []string) {
	rows, err := db.Query(sql) // 查询源端情况，默认源端、目标端表结构一致
	defer rows.Close()
	errs.CheckErr(err)
	columns, _ := rows.Columns()
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}
	var lastLineValues []interface{}
	var recordCheckSum []string

	var recordSet []map[string]string
	for rows.Next() {
		err = rows.Scan(scanArgs...)
		record := make(map[string]string)
		for i, col := range values {
			if col != nil {
				record[columns[i]] = string(col.([]byte))
			}
		}
		recordSet = append(recordSet, record)
	}

	if len(recordSet) > 0 {
		for i := 0; i < len(colNames); i++ {
			lastLineValues = append(lastLineValues, recordSet[len(recordSet)-1][colNames[i]])
		}
	}
	// 查出索引列最后一行，放入数组。checksum取出所有行放单独数组
	for i := 0; i < len(recordSet); i++ {
		recordCheckSum = append(recordCheckSum, recordSet[i]["checksum"])
	}
	return lastLineValues, recordCheckSum
}
